package com.indsvr.system.task;

import com.indsvr.common.core.domain.entity.SysDept;
import com.indsvr.common.utils.sql.JdbcUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

@Component("orgTask")
public class OrgTask {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public void sync() throws Exception {
        String url = "jdbc:mysql://192.168.2.113:3306/dgs4db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        String user = "dgs4user";
        String pwd = "Pcitc@dgs4";

        JdbcUtils connection = JdbcUtils.getConnection(url, user, pwd);

        List<OrgEntity> select = connection.select("SELECT c_oid,c_p_oid,c_code,c_p_code,c_name FROM t_bsorg", OrgEntity.class);

        if (select.size() < 1) {
            return;
        }

        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("insert into sys_dept (dept_id, parent_id , dept_name , c_code , c_p_code) values ");
        for (int i = 0; i < select.size(); i++) {
            OrgEntity orgEntity = select.get(i);
            String c_code = orgEntity.c_code;
            String c_p_code = orgEntity.c_p_code;
            String c_name = orgEntity.c_name;
            String c_oid = orgEntity.c_oid;
            String c_p_oid = orgEntity.c_p_oid;

            stringBuffer.append("("+c_oid+","+c_p_oid+",'"+c_name+"','"+c_code+"','"+c_p_code+"')");
            if (i == select.size() - 1) {
                stringBuffer.append(" ON DUPLICATE KEY UPDATE \n" +
                        "parent_id = VALUES(parent_id),\n" +
                        "dept_name = VALUES(dept_name),\n" +
                        "c_code = VALUES(c_code),\n" +
                        "c_p_code =  VALUES(c_p_code)");
                break;
            }
            stringBuffer.append(",");
        }
        Connection connection1 = null;
        PreparedStatement preparedStatement = null;

        try {
            connection1 = sqlSessionFactory.openSession().getConnection();
            preparedStatement = connection1.prepareStatement(stringBuffer.toString());
            preparedStatement.executeUpdate();
        }finally {
            try {
                preparedStatement.close();
            }catch (Exception ignored){}
            try {
                connection1.close();
            }catch (Exception ignored){}
        }

    }


    public static class OrgEntity {
        private String c_code;
        private String c_p_code;
        private String c_name;
        private String c_oid;
        private String c_p_oid;
    }


}
